package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.common.CustomException;
import com.itheima.entity.*;
import com.itheima.mapper.OrdersMapper;
import com.itheima.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 明细表业务层实现类
 *
 * @author hua
 * @since 2022/11/7 18:06
 */
@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    /**
     * 地址业务类
     */
    @Autowired
 private IAddressBookService addressBookService;
    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IOrderDetailService orderDetailService;
    /**
     * 新增订单
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        // 1.查询地址数据
        AddressBook addressBook = this.addressBookService.getById(orders.getAddressBookId());
        //如果为空,代表没有查询到任何地址
        if (addressBook ==null){
            throw new CustomException("传入的参数有误");
        }
        // 2.查询购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        //当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = this.shoppingCartService.list(queryWrapper);
        //如果购物车的数据为空,就代表这个用户购物车中没有任何内容,那么也就不能完成下单
        if (CollectionUtils.isEmpty(shoppingCartList)){
            throw  new CustomException("购物车中无任何商品,不能下单");
        }
        //主表id,也就是订单id
        long mainId = IdWorker.getId();
        //订单总价
        Integer totalAMount=0;
        // 3.组装订单明细,并给订单明细表中的主表id赋值，使其与主表产生关系
        //订单明细内容,都是购物车中的数据,所以这里遍历循环购物车的数据即可
        //订单明细集合
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
           // shoppingCart ->orderDetail
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            //主表id
            orderDetail.setOrderId(mainId);
            // 4.计算订单总价值
            //计算单个商品的总价值,然后把单个商品的总价值加到一起,就是整个订单的总价值了
            //单个商品的价格=number * amount
            // 单个商品总价 = 单价 * 数量
            //单个商品的价格
            BigDecimal price = shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber()));
            totalAMount +=price.intValue();
            //添加到保存的集合中
            orderDetails.add(orderDetail);
        }
        log.info("totalAmount ===> {}", totalAMount);
        log.info("完成了订单明细的拼装");
        //组装订单
        Orders mainOrder = new Orders();
        //主表id
        //mp在保存数据的时候,如果你要保存的那个实体类其中的id是有值,那么他就不会在给你产生一个新的id
        mainOrder.setId(mainId);
        // 订单号
       mainOrder.setNumber(mainId+ "");
       //订单状态
        mainOrder.setStatus(2);
        //当前用户id
        mainOrder.setUserId(BaseContext.getCurrentUserId());
        //地址薄id
        mainOrder.setAddressBookId(orders.getAddressBookId());
        //下单时间
        mainOrder.setOrderTime(LocalDateTime.now());
        //结账时间
        //结账时间,往往指的是付款后的时间
        //微信支付或者是支付宝支付,这些支付接口,都会有回调的
        //结账的时间可以在方法回调的时候再来写入
        mainOrder.setCheckoutTime(LocalDateTime.now());
        mainOrder.setPayMethod(orders.getPayMethod());
        //总价值
        mainOrder.setAmount(new BigDecimal(totalAMount));
        //备注
        mainOrder.setRemark(orders.getRemark());
        User user = this.userService.getById(BaseContext.getCurrentUserId());
        //下单人名称
        mainOrder.setUserName(user.getName());
        //手机号
        mainOrder.setPhone(addressBook.getPhone());
        //收货地址
        mainOrder.setAddress(addressBook.getDetail());
        //收获人
        mainOrder.setConsignee(addressBook.getConsignee());
        //6.保存订单
        this.save(mainOrder);
        //7.保存订单明细
        this.orderDetailService.saveBatch(orderDetails);
        //8.删除购物车数据
//        LambdaQueryWrapper<ShoppingCart> shoppCartQueryWrapper = new LambdaQueryWrapper<>();
//        shoppCartQueryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentUserId());
        this.shoppingCartService.remove(queryWrapper);
    }

}
